<?php
require_once ('../lib/config.php');
require_once ('../lib/facebook.php');
require_once ('../lib/friends.php');
require_once ('../lib/friend.php');
require_once ('../lib/test.php');

$facebook = new Facebook(array(
    'appId' => FB_APP_ID,
    'secret' => FB_APP_SECRET,
    'cookie' => true
));

$session = $facebook->getSession();
$me = null;

//Check if there is a session. Ensure that even if there is a session, we don't know it's valid or not until we make api call
if($session){
    try{
        $me = $facebook->api('/me');
    }catch(FacebookApiException $e){
        error_log($e);
    }
}

//Buttongs
$logout_button = "<a href='".$facebook->getLogoutUrl()."'><img src='http://static.ak.fbcdn.net/rsrc.php/z2Y31/hash/cxrz4k7j.gif'></a>"; 
$login_button = "<a href='".$facebook->getLoginUrl()."'><img src='http://static.ak.fbcdn.net/rsrc.php/zB6N8/hash/4li2k73z.gif'></a>";

if(!$me){
    print $login_button;
    exit();
}else{
    print $logout_button;
}


if($me){
    
    /*
     * inbox message function test
     */
    
    print("<br/>============================================");
    print("<br/>INBOX TEST");    
    $friends = getFriends();
    print("<br/>Number of Friends:".count($friends));
    print(countTotalNumberOfCommunication($friends));
    $inMsgs = getInboxMessages();
    print("<br/>Total Number of Inbox Messages : ".count($inMsgs));

    
    //count the number of senders
    $senders = array();
    foreach($inMsgs as $msg){
        $fId = $msg['from']['id'];
        if($fId != $me['id']){
            array_push($senders, $fId);
        }
    }
    print("<br/>Total number of unique senders : ".count($senders));
    
    processInboxMessages($friends);
    
    print(countTotalNumberOfCommunication($friends));
    

    unset($friends);
    unset($inMsgs);
    
    print("<br/>============================================");
    print("<br/>OUTBOX TEST");
    /*
     * outbox message function test
     */
    $friends = getFriends();
    print("<br/>Number of Friends:".count($friends));
    print(countTotalNumberOfCommunication($friends));
    
    $outMsgs = getOutboxMessages();
    print("<br/>Total Number of Outbox Messages : ".count($outMsgs));
    
    //count the number of unique commentors per a message and sum it

    $n = 0;
    if(is_array($outMsgs)){
        foreach ($outMsgs as $msg) {
            $receivers = array();
            $id = $msg['from']['id'];
            if($id == $me['id']){
                $receivers = $msg['to']['data'];
                if(!empty($receivers) && is_array($receivers)){
                    $n += count($receivers)-1;
                }
            }
        }
    }
    
    print("<br/>Total Sum of the number of receivers per a message : ".$n);
    processOutboxMessages($friends);
    countTotalNumberOfCommunication($friends);
        
}



?>